// pages/orderDetail/orderDetail.js
const orderApi = require('../../api/order');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderId: null,
    orderDetail: {
      // 模拟数据
      id: 1,
      orderNo: 'DD20230520123001',
      status: '待付款',
      orderTime: '2023-05-20 12:30:01',
      payTime: '',
      payMethod: '',
      remark: '不要辣，少放盐',
      address: {
        name: '林女士',
        phone: '18500557668',
        address: '金燕龙写字楼 4层电梯口（电梯可到）'
      },
      deliveryTime: '',
      dishes: [
        {
          id: 1,
          name: '宫保鸡丁',
          image: '/assets/images/dish1.jpg',
          price: 38,
          count: 1,
          spec: '微辣'
        },
        {
          id: 2,
          name: '水煮肉片',
          image: '/assets/images/dish2.jpg',
          price: 58,
          count: 1,
          spec: '特辣'
        }
      ],
      originalPrice: 96,
      deliveryFee: 5,
      discount: 0,
      totalPrice: 101,
      isEvaluated: false
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.id) {
      this.setData({
        orderId: options.id
      });
      
      // 获取订单详情
      this.getOrderDetail(options.id);
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 如果订单ID存在，刷新订单详情（可能从支付页面返回）
    if (this.data.orderId) {
      this.getOrderDetail(this.data.orderId);
    }
  },

  // 获取订单详情
  getOrderDetail(id) {
    this.setData({ loading: true });
    
    orderApi.getOrderDetail(id).then(res => {
      if (res.code === 1 && res.data) { // 注意：业务成功状态码为1
        // 处理订单状态文本
        const statusMap = {
          1: '待付款',
          2: '待接单',
          3: '已接单',
          4: '配送中',
          5: '已完成',
          6: '已取消'
        };
        
        // 处理支付方式文本
        const payMethodMap = {
          1: '微信支付',
          2: '支付宝',
          3: '余额支付'
        };
        
        // 格式化订单数据
        const orderDetail = {
          id: res.data.id,
          orderNo: res.data.number,
          status: statusMap[res.data.status] || '未知状态',
          orderTime: res.data.orderTime,
          payTime: res.data.checkoutTime,
          payMethod: payMethodMap[res.data.payMethod] || '',
          remark: res.data.remark || '',
          address: {
            name: res.data.consignee,
            phone: res.data.phone,
            address: res.data.address
          },
          deliveryTime: res.data.status === 4 ? '已送达' : res.data.estimatedDeliveryTime ? `预计${res.data.estimatedDeliveryTime}送达` : '暂无预计送达时间',
          dishes: (res.data.orderDetailList || []).map(dish => ({
            id: dish.dishId || dish.setmealId,
            name: dish.name,
            image: dish.image,
            price: dish.amount,
            count: dish.number,
            spec: dish.dishFlavor
          })),
          originalPrice: res.data.amount - (res.data.packAmount || 0),
          deliveryFee: res.data.packAmount || 5,
          discount: 0, // 接口未提供优惠金额，默认为0
          totalPrice: res.data.amount,
          isEvaluated: false // 接口未提供评价状态，默认为未评价
        };
        
        this.setData({
          orderDetail: orderDetail
        });
      } else {
        wx.showToast({
          title: res.msg || '获取订单详情失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      wx.showToast({
        title: '获取订单详情失败',
        icon: 'none'
      });
      console.error('获取订单详情失败:', err);
    }).finally(() => {
      this.setData({ loading: false });
    });
  },

  // 复制订单编号
  copyOrderNo() {
    wx.setClipboardData({
      data: this.data.orderDetail.orderNo,
      success: () => {
        wx.showToast({
          title: '复制成功',
          icon: 'success'
        });
      }
    });
  },

  // 联系商家
  contactRestaurant() {
    wx.makePhoneCall({
      phoneNumber: '10086', // 模拟商家电话
      fail: () => {
        wx.showToast({
          title: '拨打电话失败',
          icon: 'none'
        });
      }
    });
  },

  // 再来一单
  orderAgain() {
    const orderId = this.data.orderId;
    
    // 显示加载中
    wx.showLoading({
      title: '处理中...',
      mask: true
    });
    
    // 调用再来一单API
    orderApi.repeatOrder(orderId).then(res => {
      if (res.code === 1) { // 注意：业务成功状态码为1
        wx.hideLoading();
        wx.showToast({
          title: '已添加到购物车',
          icon: 'success',
          duration: 1500,
          success: () => {
            setTimeout(() => {
              // 跳转到首页并显示购物车
              wx.switchTab({
                url: '/pages/index/index',
                success: () => {
                  // 设置一个标记，表示需要显示购物车
                  getApp().globalData.showCartAfterRedirect = true;
                }
              });
            }, 1500);
          }
        });
      } else {
        wx.hideLoading();
        wx.showToast({
          title: res.msg || '操作失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('再来一单失败:', err);
      wx.hideLoading();
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    });
  },

  // 去支付
  goToPay() {
    wx.navigateTo({
      url: `/pages/payment/payment?orderId=${this.data.orderId}`
    });
  },

  // 去评价
  goToEvaluate() {
    wx.navigateTo({
      url: `/pages/evaluate/evaluate?orderId=${this.data.orderId}`
    });
  },

  // 取消订单
  cancelOrder() {
    wx.showModal({
      title: '提示',
      content: '确定要取消该订单吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '处理中...',
            mask: true
          });

          orderApi.cancelOrder(this.data.orderId).then(res => {
            if (res.code === 1) {
              wx.showToast({
                title: '订单已取消',
                icon: 'success',
                duration: 1500
              });
              // 刷新订单详情
              this.getOrderDetail(this.data.orderId);
            } else {
              wx.showToast({
                title: res.msg || '取消订单失败',
                icon: 'none'
              });
            }
          }).catch(err => {
            console.error('取消订单失败:', err);
            wx.showToast({
              title: '取消订单失败',
              icon: 'none'
            });
          }).finally(() => {
            wx.hideLoading();
          });
        }
      }
    });
  },

  // 催单
  reminderOrder() {
    wx.showLoading({
      title: '处理中...',
      mask: true
    });

    orderApi.reminderOrder(this.data.orderId).then(res => {
      if (res.code === 1) {
        wx.showToast({
          title: '已通知商家加快处理',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: res.msg || '催单失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('催单失败:', err);
      wx.showToast({
        title: '催单失败',
        icon: 'none'
      });
    }).finally(() => {
      wx.hideLoading();
    });
  },
  
  // 返回上一页
  goBack() {
    wx.navigateBack();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})